<!--  -->
<template>
  <div class="user-manage">
    <div class="query-form">
      <el-form ref="form" :inline="true" :model="user">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="user.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-input v-model="user.userName" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select v-model="user.state">
            <el-option :value="0" label="所有"></el-option>
            <el-option :value="1" label="在职"></el-option>
            <el-option :value="2" label="离职"></el-option>
            <el-option :value="3" label="试用期"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset('form')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="base-table">
      <div class="action">
        <el-button
          type="primary"
          @click="handleCreate"
          v-has:add="'user-create'"
          >新增</el-button
        >
        <el-button
          type="danger"
          @click="handlePatchDel"
          v-has:add="'user-patch-delete'"
          >批量删除</el-button
        >
      </div>
      <el-table :data="userList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column
          v-for="item in columns"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
          :formatter="item.formatter"
        />
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(scope.row)"
              v-has:add="'user-edit'"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="small"
              @click="handleDel(scope.row)"
              v-has:add="'user-delete'"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination"
        background
        layout="prev, pager, next"
        :total="pager.total"
        :page-size="pager.pageSize"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog title="用户新增" v-model="showModal">
      <el-form
        ref="dialogForm"
        :model="userForm"
        label-width="100px"
        :rules="rules"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input
            v-model="userForm.userName"
            :disabled="action === 'edit'"
            placeholder="请输入用户名称"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail">
          <el-input
            v-model="userForm.userEmail"
            :disabled="action === 'edit'"
            placeholder="请输入用户邮箱"
          >
            <template #append> @imooc.com </template>
          </el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="userForm.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="岗位" prop="job">
          <el-input v-model="userForm.job" placeholder="请输入岗位" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select v-model="userForm.state">
            <el-option label="在职" :value="1" />
            <el-option label="离职" :value="2" />
            <el-option label="试用期" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="系统角色" prop="roleList">
          <el-select
            v-model="userForm.roleList"
            placeholder="请选择用户系统角色"
            multiple
            style="width: 100%"
          >
            <el-option
              v-for="role in roleList"
              :key="role._id"
              :label="role.roleName"
              :value="role._id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-cascader
            v-model="userForm.deptId"
            placeholder="请选择所属部门"
            :options="deptList"
            :props="{ checkStrictly: true, value: '_id', label: 'deptName' }"
            clearable
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer"></span>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance, reactive, toRaw, nextTick } from "vue";
import utils from "../utils/utils";

const { proxy } = getCurrentInstance();

const user = ref({
  state: 1,
});

const userList = ref([]);
const pager = ref({
  pageNum: 1,
  pageSize: 10,
});
const columns = ref([
  {
    label: "用户ID",
    prop: "userId",
  },
  {
    label: "用户名称",
    prop: "userName",
  },
  {
    label: "用户邮箱",
    prop: "userEmail",
  },
  {
    label: "用户角色",
    prop: "role",
    formatter(row, column, value) {
      return {
        0: "管理员",
        1: "普通用户",
      }[value];
    },
  },
  {
    label: "用户状态",
    prop: "state",
    formatter(row, column, value) {
      return {
        1: "在职",
        2: "离职",
        3: "试用期",
      }[value];
    },
  },
  {
    label: "注册时间",
    prop: "createTime",
    width: 200,
    formatter: (row, column, value) => {
      return utils.formateDate(new Date(value));
    },
  },
  {
    label: "最后登录时间",
    prop: "lastLoginTime",
    width: 200,
    formatter: (row, column, value) => {
      return utils.formateDate(new Date(value));
    },
  },
]);

const checkedUserIds = ref([]);
const showModal = ref(false);

const dialogForm = ref(null);
const userForm = reactive({
  userName: "",
  userEmail: "",
  mobile: "",
  job: "",
  state: 3,
  roleList: [],
  deptId: "",
});

const roleList = ref([]);
const deptList = ref([]);

const action = ref("add");

const rules = ref({
  userName: [{ required: true, message: "请输入用户名称", trigger: "blur" }],
  userEmail: [{ required: true, message: "请输入用户邮箱", trigger: "blur" }],
  deptId: [{ required: true, message: "请输入用户邮箱", trigger: "blur" }],
  mobile: [
    {
      pattern: /1\d{10}/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
});

const getUserList = async () => {
  let params = { ...user.value, ...pager.value };
  try {
    const { list, page } = await proxy.$api.getUserList(params);
    userList.value = list;
    pager.value.total = page.total;
  } catch (error) {}
};

getUserList();

const handleQuery = () => {
  getUserList();
};

// const form = ref(null);
const handleReset = (form) => {
  if (!form) return;
  // form.resetFields();
  proxy.$refs[form].resetFields();
};

const handleCurrentChange = (current) => {
  pager.value.pageNum = current;
  getUserList();
};

const handleEdit = async (row) => {
  action.value = "edit";
  showModal.value = true;
  // proxy.$nextTick(() => {
  await nextTick();
  Object.assign(userForm, row);
  // });
};

const handleDel = async (row) => {
  await proxy.$api.userDel({
    userIds: [row.userId],
  });
  proxy.$message.success("删除成功");
  getUserList();
};

const handlePatchDel = async () => {
  if (checkedUserIds.value.length == 0) {
    proxy.$message.error("请选择要删除的用户");
    return;
  }
  const res = await proxy.$api.userDel({
    userIds: checkedUserIds.value,
  });
  if (res.modifiedCount > 0) {
    proxy.$message.success("删除成功");
    getUserList();
  } else {
    proxy.$message.error("修改失败");
  }
};

const handleSelectionChange = (list) => {
  let arr = [];

  list.map((item) => {
    arr.push(item.userId);
  });
  checkedUserIds.value = arr;
};

const handleCreate = () => {
  action.value = "add";
  showModal.value = true;
};

const getDeptList = async () => {
  let list = await proxy.$api.getDeptList();
  deptList.value = list;
};
getDeptList();

const getRoleAllList = async () => {
  let list = await proxy.$api.getRoleAllList();
  roleList.value = list;
};
getRoleAllList();

const handleClose = () => {
  showModal.value = false;
  handleReset("dialogForm");
};

const handleSubmit = () => {
  proxy.$refs.dialogForm.validate(async (valid) => {
    if (valid) {
      let params = toRaw(userForm);
      params.UserEmail += "@imooc.com";
      params.action = action.value;
      // console.log(params);
      let res = await proxy.$api.userSubmit(params);
      showModal.value = false;
      proxy.$message.success("用户创建成功");
      handleReset("dialogForm");
      getUserList();
    }
  });
};
</script>
<style lang="scss"></style>
